package org.ccay.web.support.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ccay.core.ioc.Ccay;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.request.impl.RequestContext;
import org.ccay.core.util.MimeTypeUtil;
import org.ccay.core.util.StringUtil;
import org.ccay.i18n.I18nVO;
import org.ccay.i18n.service.II18nQueryService;
import org.ccay.registry.util.RegistryQueryUtil;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;


/**
 * I180使用的servlet
 * 
 * @since 2011-12-14
 */
@Named("/servlet/i18n")
public class I18nServlet extends CacheServlet{
	private static ILogger logger = CcayLoggerFactory.getLogger(I18nServlet.class);

	
	private static final long serialVersionUID = 7708801848791178664L;	
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置头文件
		response.setContentType(MimeTypeUtil.getTypeBySuffix("json"));
		response.setCharacterEncoding("UTF-8");
		
		String lang = request.getParameter("lang");
		
		//获取优选语种
		if(StringUtil.isNullOrEmpty(lang)){
			lang =  RequestContext.getCurrent().getUserLanguage();
		}
		
		II18nQueryService i18nService = (II18nQueryService)Ccay.getContext().getBean("i18nQueryService");;
		//查询数据
		List<I18nVO> i18ns = i18nService.findI18nList(null,  lang);
		
		PrintWriter out = response.getWriter();
		//迭代输出资源数据
		JsonNodeFactory factory = JsonNodeFactory.instance;
		ObjectNode rootNode = factory.objectNode();
		for(int i=0;i<i18ns.size();i++){
			I18nVO i18nvo = i18ns.get(i);
			//不需要将枚举型的国际化发送给前台
			if(i18nvo.getI18nKey().startsWith("Enum.")){
				continue;
			}
			rootNode.put(i18nvo.getI18nKey().trim(), i18nvo.getI18nContent());
		}
		out.print(rootNode.toString());
		out.flush();
		out.close();
	}
	
	protected int getCacheMaxAge() {
		return RegistryQueryUtil.getIntegerValue("Ccay.GlobalParamters.I18nCache");
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
